/*    
    OpenMheg - A free MHEG-5 library
    Copyright (C) 2008 Dharmesh Malam

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Core.Model.Ingredients.Links;

namespace XMHEGDecoder.Builders
{
    public class LinkBuilder
    {
        public static Link Build ( XmlElement node )
        {
            Link ret = new Link();
            IngredientBuilder.Build( node, ret );

            XmlElement e;
            
            e = node[ "link-condition" ];
            if ( e != null )
                ret.LinkCondition = BuildLinkCondition( e );

            e = node[ "link-effect" ];
            if ( e != null )
                ret.LinkEffect = ActionBuilder.Build( e );

            return ret;
        }

        public static LinkCondition BuildLinkCondition ( XmlElement node )
        {
            LinkCondition ret = new LinkCondition();

            XmlElement e;
             
            e = node["event-source" ];
            if ( e != null )
                ret.EventSource = ObjectRefBuilder.Build( e );

            e = node[ "event-type" ];
            if ( e != null )
                ret.EventType = Core.Model.Events.Event.getEvent( DecodeUtils.ParseInt( e.InnerText ) );

            e = node[ "event-data" ];
            if ( e != null )
            {
                XmlElement t;
                 
                t =  e[ "boolean" ];
                if ( t != null )
                    ret.EventData =  DecodeUtils.ParseBool(t.InnerText) ;
                else
                {
                    t = e[ "octetstring" ];
                    if ( t != null )
                        ret.EventData = DecodeUtils.DecodeBase64( t.InnerText );
                    else
                    {
                        t = e[ "integer" ];
                        if ( t != null )
                            ret.EventData = DecodeUtils.ParseInt( t.InnerText) ;
                    }
                }
            }

            return ret;
        }
    }
}
